<script setup>
import {
  onMounted,
  ref,
  reactive,
  toRefs,
  getCurrentInstance,
  toRaw,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import utils from "@/utils/utils";
import QueryForm from "../../../packages/QueryForm/QueryForm.vue";

import BaseTable from "../../../packages/BaseTable/BaseTable.vue";

// getCurrentInstance方法只能在setup函数中使用，想要获取到上下文并获得全局挂载方法需要使用proxy属性进行调用
const { proxy } = getCurrentInstance();
const data = reactive({
  user: { status: 0, gender: "" },
  columns: [],
  userList: [],
});
// 初始化分页对象
const pager = reactive({
  pageNum: 1,
  pageSize: 10,
});
// 定义输入自定义组件的参数 -- 相当于用户输入的自定义json
const form = [
  {
    type: "input",
    label: "用户名",
    model: "userName",
    placeholder: "请输入用户名",
  },
  {
    type: "select",
    label: "状态",
    model: "status",
    placeholder: "请选择状态",
    options: [
      {
        label: "全部",
        value: 2,
      },
      {
        label: "启用",
        value: 0,
      },
      {
        label: "禁用",
        value: 1,
      },
    ],
  },
  // {
  //   type: "select",
  //   label: "所属机构",
  //   model: "dept",
  //   placeholder: "请选择所属机构",
  //   options: [
  //     {
  //       label: "总经办",
  //       value: 0,
  //     },
  //     {
  //       label: "生产部",
  //       value: 1,
  //     },
  //     {
  //       label: "IT部",
  //       value: 2,
  //     },
  //     {
  //       label: "电商部",
  //       value: 3,
  //     },
  //     {
  //       label: "收购部",
  //       value: 4,
  //     },
  //   ],
  // },
  {
    type: "input",
    label: "真实姓名",
    model: "realName",
    placeholder: "请输入真实姓名",
  },
  {
    type: "input",
    label: "手机号码",
    model: "phonenumber",
    placeholder: "请输入手机号码",
  },
  {
    type: "select",
    label: "性别",
    model: "gender",
    placeholder: "请选择性别",
    options: [
      {
        label: "全部",
        value: "",
      },
      {
        label: "男",
        value: 0,
      },
      {
        label: "女",
        value: 1,
      },
    ],
  },
];
// 动态表格格式
data.columns = [
  {
    type: "selection",
  },
  {
    label: "序号",
    prop: "userId",
  },
  {
    label: "用户名",
    prop: "userName",
  },
  {
    label: "真实姓名",
    prop: "realName",
  },
  {
    label: "所属机构",
    prop: "dept",
    formatter(row, column, value) {
      return (value && value.deptName) || "暂无机构";
    },
  },
  {
    label: "用户角色",
    prop: "roles",
    // 规则校验对当前数据进行格式转换
    formatter(row, column, value) {
      return toRaw(value)
        .map((item) => item.roleName)
        .join("/");
    },
  },
  {
    label: "性别",
    prop: "gender",
    formatter(row, column, value) {
      return {
        0: "男",
        1: "女",
      }[value];
    },
  },
  {
    label: "电子邮箱",
    prop: "email",
  },
  {
    label: "手机号码",
    prop: "phonenumber",
  },
  {
    label: "状态",
    prop: "status",
    formatter(row, column, value) {
      return {
        0: "启用",
        1: "禁用",
      }[value];
    },
  },
  {
    label: "操作",
    type: "action",
    width: 360,
    list: [
      {
        text: "删除",
        type: "danger",
      },
      {
        text: "重置密码",
        type: "warning",
      },
      {
        text: "编辑",
        type: "primary",
      },
      {
        text: "分配角色",
        type: "",
      },
    ],
  },
];
// 弹框显示
let showModel = ref(false);
// 新增用户
const userForm = reactive({ status: 1 });
// 定义表单校验规则
const rules = reactive({
  userName: [
    {
      required: true,
      message: "请输入用户名称",
      trigger: "blur",
    },
  ],
  userEmail: [
    {
      required: true,
      message: "请输入用户邮箱",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      pattern: /1\d{10}/,
      message: "请输入正确的手机号格式",
      trigger: "blur",
    },
  ],
});
// 选中用户列表的对象
let checkedUserIds = ref([]);
// 角色列表
const roleList = ref([]);
// 用户创建行为
const action = ref("add");
// 分配角色弹框
const showRolesModals = ref(false);
const userId = ref("");

// 获取用户账号列表
const getOperationUserList = async () => {
  let params = { ...data.user, ...pager };

  try {
    if (params.status == 2) {
      params.status = '';
    }
    const { list, pageNum, pageSize, total } =
      await proxy.$api.getOperationUser(params);
    data.userList = list;
    pager.total = total;
    pager.pageNum = pageNum;
    pager.pageSize = pageSize;
  } catch (err) {
    console.log(err);
  }
};

onMounted(() => {
  // 初始化获取用户列表
  getOperationUserList();
  // 获取机构信息
  getDeptMessage();
  getRoleAllList();
});
// 查询事件，获取用户列表
const handleQuery = () => {
  getOperationUserList();
};
// 表格每一项后面action按钮对应的操作
const handleAction = ({ index, row }) => {
  console.log(index, row);
  if (index == 0) {
    // 删除
    handleDel(row);
  } else if (index == 1) {
    // 重置密码
    resetUserPassword(row);
  } else if (index == 2) {
    // 编辑
    handleEdit(row);
  } else if (index == 3) {
    // 分配角色
    handleRole(row);
  }
};
// 重置查询表单
const handleReset = (form) => {
  proxy.$refs?.[form].resetFields();
};
// 重置密码
const resetUserPassword = async (row) => {
  ElMessageBox.alert("确认重置密码吗？", "重置密码", {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: "OK",
    callback: async (action) => {
      if (action === "cancel") return;
      try {
        await proxy.$api.resetUserPassword({
          userId: row.userId,
        });
        proxy.$message.success("重置密码成功！");
      } catch (error) {
        proxy.$message.error(`重置密码失败，请稍后再试：${error.message}`);
      }
    },
  });
};
// 切换页号
const handleCurrentChange = (current) => {
  pager.pageNum = current;
  getOperationUserList();
};
// 分配角色
const handleRole = async (row) => {
  showRolesModals.value = true;
  userId.value = row.userId;
};
// 禁用
const handleDisabled = async () => {
  if (checkedUserIds.value.length == 0) {
    proxy.$message.error("请选择要禁用的用户");
    return;
  }
  try {
    await proxy.$api.changeStatus({
      userIds: [...toRaw(checkedUserIds.value)],
      status: 1,
    });
    proxy.$message.success("账户禁用成功！");
  } catch (error) {
    proxy.$message.error(`账户禁用失败，请稍后再试：${error.message}`);
  }

  getOperationUserList();
};
// 启用
const handleEnabled = async () => {
  if (checkedUserIds.value.length == 0) {
    proxy.$message.error("请选择要启用的用户");
    return;
  }
  try {
    await proxy.$api.changeStatus({
      userIds: [...toRaw(checkedUserIds.value)],
      status: 0,
    });
    proxy.$message.success("账户启用成功！");
  } catch (error) {
    proxy.$message.error(`账户启用失败，请稍后再试：${error.message}`);
  }

  getOperationUserList();
};
// 单一用户删除
const handleDel = async (row) => {
  await proxy.$api.userDel({
    userIds: [row.userId],
  });
  proxy.$message.success("删除成功");
  getOperationUserList();
};
// 批量用户删除
const handlePatchDel = async () => {
  if (checkedUserIds.value.length == 0) {
    proxy.$message.error("请选择要删除的用户");
    return;
  }
  const res = await proxy.$api.userDel({
    userIds: checkedUserIds.value,
  });
  if (res) {
    proxy.$message.success("删除成功");
    getOperationUserList();
  }
};
// 表格多选
const handleSelectionChange = (list) => {
  let arr = [];
  console.log(list);
  list.map((item) => {
    arr.push(item.userId);
  });
  checkedUserIds.value = arr;
};
// 用户新增
const handleCreate = () => {
  action.value = "add";
  showModel.value = true;
};
// 获取角色列表
const getRoleAllList = async () => {
  const res = await proxy.$api.getRoleAllList();
  const list = res.map((item) => ({
    id: item.roleId,
    roleName: item.roleName,
  }));
  roleList.value = list;
};
// 用户弹窗关闭
const handleClose = () => {
  showModel.value = false;
  handleReset("logoForm");
};
// 提交
const handleSubmit = () => {
  //提交前校验
  proxy.$refs.logoForm.validate(async (valid) => {
    if (valid) {
      // 将响应式对象转为普通对象
      let params = { ...toRaw(userForm), deptId: deptValue.value };
      // 新增 / 修改
      const res = await proxy.$api.userSubmit(params, action.value);
      if (res) {
        showModel.value = false;
        proxy.$message.success(
          `${action.value === "add" ? "用户创建成功" : "用户更新成功"}`
        );
        handleReset("logoForm");
        getOperationUserList();
      }
    }
  });
};
// 保存分配角色
const handleAssignRoles = async () => {
  const roleIds = roleList.value
    .filter((item) => item.roleId)
    .map((item) => item.id);
  // let userIdList = [userId.value, ...checkedUserIds.value];
  try {
    await proxy.$api.assignRoles({
      userId: userId.value,
      // userId: userIdList,
      roleIds,
    });
    proxy.$message.success("角色分配成功");
  } catch (error) {
    proxy.$message.error("角色分配失败，请稍后再试。。。");
  }
  // 用户id置为空
  userId.value = "";
  roleList.value = roleList.value.map((item) => {
    item.roleId = false;
    return item;
  });
  showRolesModals.value = false;
  getOperationUserList();
};
// 取消角色分配
const handleCancelAssignRoles = () => {
  showRolesModals.value = false;
  userId.value = "";
  roleList.value = roleList.value.map((item) => {
    item.roleId = false;
    return item;
  });
};
const deptData = ref([]);
const deptValue = ref("");
const getDeptMessage = async () => {
  try {
    const res = await proxy.$api.getDeptMessage();

    function normalizeDeptData(arr) {
      arr.forEach((item) => {
        console.log(item);
        item.value = item.deptId;
        item.label = item.deptName;
        if (item.children) normalizeDeptData(item.children);
      });

      return arr;
    }

    deptData.value = normalizeDeptData(res);
  } catch (error) { }
};
// 用户信息编辑
const handleEdit = async (row) => {
  action.value = "edit";

  // 在下一个生命周期执行
  await proxy.$nextTick(() => {
    // 使用浅拷贝将值赋给userForm
    const obj = {
      ...row,
      roleIds: toRaw(row.roles).map((item) => item.roleId),
    };
    deptValue.value = row?.dept?.deptId;
    Object.assign(userForm, obj);
  });

  showModel.value = true;
};
const { user, columns, userList } = toRefs(data);
</script>

<template>
  <div class="user-manage">
    <div class="query-form">
      <query-form :form="form" v-model="user" @handleQuery="handleQuery"></query-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary" @click="handleCreate">新增</el-button>
        <!-- <el-button @click="handleRole">分配角色</el-button> -->
        <el-button type="danger" @click="handlePatchDel">删除</el-button>
        <el-button type="info" @click="handleDisabled">禁用</el-button>
        <el-button type="success" @click="handleEnabled">启用</el-button>
      </div>
      <base-table :pager="pager" :columns="columns" :data="userList" @selection-change="handleSelectionChange"
        @handleAction="handleAction" @handleCurrentChange="handleCurrentChange">
        <template v-slot="action">
          <el-button type="primary" @click="handleCreate" v-has="'user-create'">新增</el-button>
          <el-button type="danger" @click="handlePatchDel" v-has="'user-patch-delete'">批量删除</el-button>
        </template>
      </base-table>
    </div>
    <el-dialog :title="action === 'add' ? '新增账户' : '修改账户信息'" v-model="showModel">
      <el-form ref="logoForm" :model="userForm" label-width="100" :rules="rules">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="所属机构" prop="deptId">
          <el-tree-select v-model="deptValue" :data="deptData" :render-after-expand="false" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="userForm.roleIds" placeholder="请选择用户系统角色" multiple style="width: 100%">
            <el-option v-for="item in roleList" :key="item.id" :value="item.id" :label="item.roleName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入电子邮箱">
          </el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="userForm.phonenumber" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="分配角色" v-model="showRolesModals">
      <div>
        <el-checkbox v-for="item in roleList" v-model="item.roleId" :label="item.roleName" size="large" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancelAssignRoles">取消</el-button>
          <el-button type="primary" @click="handleAssignRoles">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.user-manage {
  height: 100%;
  overflow-y: scroll;
}

.query-form {
  display: flex;
  align-items: center;
  background: #fff;
  padding-top: 18px;
  margin-bottom: 16px;
  padding-left: 20px;
  border-radius: 4px;
}

.base-table {
  background: #fff;
  border-radius: 4px;

  .action {
    padding: 15px;
    border-bottom: 1px solid #eee;
  }
}

.pagination {
  justify-content: flex-end;
  padding: 8px 20px;
}
</style>
